package com.paraport;

import java.io.BufferedReader;

import javax.comm.CommPortIdentifier;
import javax.comm.NoSuchPortException;
import javax.comm.ParallelPort;
import javax.comm.PortInUseException;
import javax.comm.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Scanner;
import ch.aplu.util.LptPort;

public class ParallelClient {
	
	/**
	* Initialize connection to the phone
	*
	*/
	
	// TCP Socket
	PrintWriter out;
	Socket socket;
	Scanner sc;
	BufferedReader in;
	OutputStreamWriter LptOut;
	int baseAddress = 0x378;
	//LPT Port
	static Enumeration<?> portList;
	static CommPortIdentifier portId;
	ParallelPort parallelPort;
	
	public void execAdb() 
	{
		// run the adb bridge
		try 
		{
			Process p=Runtime.getRuntime().exec("C:\\android-sdk-windows\\platform-tools\\adb.exe forward tcp:38300 tcp:38300");
			Scanner sc = new Scanner(p.getErrorStream());
			if (sc.hasNext()) 
			{
				while (sc.hasNext()) System.out.println(sc.next());
				System.out.println("Cannot start the Android debug bridge");
			}
		}
		catch (Exception e) 
		{
			System.out.println("fatalError"+(e.toString()));
		}
	}


	public void initializeConnection() throws PortInUseException, UnsupportedCommOperationException, IOException, NoSuchPortException, InterruptedException
	{
		// Parallel Port find and initialize
		
		//portId = CommPortIdentifier.getPortIdentifier("LPT1");
		//parallelPort = (ParallelPort) portId.open("Parallel",0);
		//parallelPort.setMode(ParallelPort.LPT_MODE_SPP);
		//LptOut = new OutputStreamWriter(parallelPort.getOutputStream());
		System.loadLibrary("jlptport");
		System.out.println("Opening Parallel Port...");
		LptPort lpt1 = new LptPort();
		
		int rc = lpt1.open(baseAddress);
		if(rc == 0)
			System.out.println("OK");
		else
		{
			System.out.println("failed");
			return;
		}
			
		
		//Create socket connection
		try
		{
			System.out.println("Opening TCP Client Connection to SFD_Numbers....");
			socket = new Socket("192.168.43.1", 3233);
			//out = new PrintWriter(socket.getOutputStream(), true);
			
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			System.out.println("OK");
			//sc = new Scanner(socket.getInputStream());
			
			System.out.print("Receiving Triggers and writing them to parallelport");
			while (!in.ready())
			{
				
				if(in.read()>0)
				{
					
					//System.out.println(in.read()); // Read one line and output it
					
					lpt1.writeData(in.read()+10);
					Thread.sleep(2);
					lpt1.writeData(0x000);
					System.out.print(".");

					//lpt1.writeControl(0x05);
					
					
					
					//LptOut.close();
					//System.out.print("\n");
				}
				//else
				//{
					//sc.close();
					//in.close();
					//socket.close();
					//lpt1.close();
					//break;
				//}
			}
	        in.close();
			//sc.close();
			socket.close();
			lpt1.close();


			// add a shutdown hook to close the socket if system crashes or exists unexpectedly
			Thread closeSocketOnShutdown = new Thread() 
			{
				public void run() 
				{
					try 
					{
						//sc.close();
						in.close();
						socket.close();
						System.out.println("\nEND");
						System.out.println("TCP Connection to SFD_Numbers has Closed");
					} 
					catch (IOException e) 
					{
						e.printStackTrace();
					}
				}
			};
			Runtime.getRuntime().addShutdownHook(closeSocketOnShutdown);
		} 
		catch (UnknownHostException e)
		{
			System.out.println("Socket connection problem (Unknown host)"+e.getStackTrace());
		}
		catch (IOException e) 
		{
			System.out.println("Could not initialize I/O on socket "+e.getStackTrace());
		}		
	}
}
